

document.addEventListener('DOMContentLoaded', () => {
  const chatBox = document.getElementById('chat-box');
  const userInput = document.getElementById('user-input');
  const sendBtn = document.getElementById('send-btn');

  // 创建并返回一个消息 DOM 节点
  function createMessageElement(sender) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('chat-message', sender);
    chatBox.appendChild(messageElement);
    chatBox.scrollTop = chatBox.scrollHeight;
    return messageElement;
  }

  // 普通用于追加完整消息的函数（若需要保留）
  function appendMessage(message, sender) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('chat-message', sender);
    messageElement.textContent = message;
    chatBox.appendChild(messageElement);
    chatBox.scrollTop = chatBox.scrollHeight;
  }

  // 处理发送消息，并使用流式输出展示回复
  async function sendMessage() {
    const message = userInput.value.trim();
    if (!message) return;
    appendMessage(message, 'user');
    
    let askData = {
      "messages": [{ "role": "user", "content": userInput.value }],
      "model": "qwen2.5:3b",
      "options": {}
    };
    let botMessageElement = createMessageElement('bot');
    
    try {
      const response = await fetch("https://api.deepseek.com/chat/completions", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization':'Bearer sk-de11e7d34ff2413c9228e583a937865b'
        },
        body: JSON.stringify(askData)
      })
      const data = await response.text();
      const arrayString = '[' + data.trim().replace(/}\s*{/g, '},{') + ']';
      let jsonArray;
      try {
        userInput.value = '';
        jsonArray = JSON.parse(arrayString);
        jsonArray.forEach(element => {
          botMessageElement.textContent += element.message.content;
          chatBox.scrollTop = chatBox.scrollHeight;
        });
      } catch (e) {
        console.error("解析 JSON 失败", e);
        return "";
      }
    } catch (error) {
      console.error("请求失败", error);
    }
  }

  // 点击按钮或回车键发送消息
  // sendBtn.addEventListener('click', sendMessage);
  userInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      sendMessage();
    }
  });
});

